// 颜色配置
const XMLG_COLORS = [
  '#F8BBD9', '#F48FB1', '#F06292', '#EC407A', '#E91E63',
  '#DDA0DD', '#DA70D6', '#BA55D3', '#9370DB', '#8A2BE2'
]

// 弹幕文本
const danmuTexts = [
  '欢迎学弟学妹们报考厦门理工学院',
  '厦门理工学院AI助手真好用！',
  '希望煮包多加点功能到这个AI上，求求了！',
  '厦门理工怎么还不改名啊，被忽悠好久了',
  '隔壁都改名了，厦门理工还不改名，回答我？',
  '厦门理工学院三期宿舍这边的旺角美食城好多吃的，真的好吃！！！',
  '集美苑3号楼的903的舍长好帅啊啊啊！！！',
  '周同学真的太卷了，卷不过他！！！',
  '跟着美哥每天都能薅到羊毛，嘻嘻！！！',
  '有喜欢打瓦的妹妹吗，让我宝哥带你，他会颗秒噢',
  '那个p哥啥也不会，就只会吹牛'
]

// CSS样式
const DANMAKU_STYLES = `
.custom-danmaku-layer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: 5;
  pointer-events: none;
  overflow: hidden;
}

.custom-danmaku-item {
  position: absolute;
  font-weight: 500;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);
  background: rgba(255, 255, 255, 0.9);
  border-radius: 20px;
  padding: 8px 16px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(3px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  white-space: nowrap;
  transition: all 0.3s ease;
}

.custom-danmaku-item:hover {
  transform: scale(1.05);
  z-index: 10;
}
`

// 动态轨道管理器
class DanmakuManager {
  constructor() {
    this.activeDanmus = []
    this.timer = null
    this.stylesInjected = false
    this.updateCallback = null
    this.getMessagesLength = null
    this.trackOccupied = new Set() // 记录被占用的轨道
  }

  // 注入样式
  injectStyles() {
    if (this.stylesInjected) return
    const style = document.createElement('style')
    style.textContent = DANMAKU_STYLES
    document.head.appendChild(style)
    this.stylesInjected = true
  }

  // 动态计算可用轨道
  getAvailableTrack() {
    const screenHeight = window.innerHeight
    const trackHeight = 55 // 稍微减小轨道高度，增加轨道数量

    // 计算上下区域 - 上35%，下45%
    const topAreaHeight = screenHeight * 0.35
    const bottomAreaStart = screenHeight * 0.55 // 从55%开始，留20%给中间区域
    const bottomAreaHeight = screenHeight * 0.45

    // 计算每个区域的轨道数量
    const topTracks = Math.floor(topAreaHeight / trackHeight)
    const bottomTracks = Math.floor(bottomAreaHeight / trackHeight)

    // 生成所有可用轨道位置
    const allTracks = []

    // 上区域轨道
    for (let i = 0; i < topTracks; i++) {
      allTracks.push({
        id: `top-${i}`,
        top: 30 + (i * trackHeight), // 从30px开始
        area: 'top'
      })
    }

    // 下区域轨道
    for (let i = 0; i < bottomTracks; i++) {
      allTracks.push({
        id: `bottom-${i}`,
        top: bottomAreaStart + (i * trackHeight),
        area: 'bottom'
      })
    }

    // 查找空闲轨道
    const availableTracks = allTracks.filter(track => !this.trackOccupied.has(track.id))

    if (availableTracks.length > 0) {
      // 随机选择一个空闲轨道
      const selectedTrack = availableTracks[Math.floor(Math.random() * availableTracks.length)]

      // 标记轨道为占用状态，2.5秒后自动释放（缩短占用时间）
      this.trackOccupied.add(selectedTrack.id)
      setTimeout(() => {
        this.trackOccupied.delete(selectedTrack.id)
      }, 2500)

      return selectedTrack
    }

    // 如果所有轨道都被占用，随机选择一个
    return allTracks[Math.floor(Math.random() * allTracks.length)]
  }

  // 创建弹幕
  createDanmu() {
    const screenWidth = window.innerWidth
    const track = this.getAvailableTrack()
    return {
      id: Date.now() + Math.random(),
      text: danmuTexts[Math.floor(Math.random() * danmuTexts.length)],
      color: XMLG_COLORS[Math.floor(Math.random() * XMLG_COLORS.length)],
      fontSize: 18,
      top: track.top,
      left: screenWidth + 50,
      speed: 80,
      trackId: track.id
    }
  }

  // 移动弹幕
  moveDanmu(danmu) {
    danmu.left -= danmu.speed / 60
    return danmu.left > -500
  }

  // 启动弹幕
  start(updateCallback, getMessagesLengthCallback) {
    this.updateCallback = updateCallback
    this.getMessagesLength = getMessagesLengthCallback
    this.injectStyles()

    if (this.getMessagesLength && this.getMessagesLength() > 0) return

    this.stop()

    // 立即创建第一个弹幕
    this.addDanmu()

    // 每1.5秒创建一个新弹幕（增加频率）
    this.timer = setInterval(() => {
      if (this.getMessagesLength && this.getMessagesLength() > 0) {
        this.stop()
        return
      }
      this.addDanmu()
    }, 1500) // 从2秒减少到1.5秒

    this.animate()
  }

  // 添加弹幕
  addDanmu() {
    const danmu = this.createDanmu()
    this.activeDanmus.push(danmu)
    this.notifyUpdate()
  }

  // 动画循环
  animate() {
    if (this.timer === null) return

    this.activeDanmus = this.activeDanmus.filter(danmu => this.moveDanmu(danmu))
    this.notifyUpdate()

    requestAnimationFrame(() => this.animate())
  }

  // 通知更新
  notifyUpdate() {
    if (this.updateCallback) {
      this.updateCallback([...this.activeDanmus])
    }
  }

  // 停止弹幕
  stop() {
    if (this.timer) {
      clearInterval(this.timer)
      this.timer = null
    }
    this.activeDanmus = []
    this.trackOccupied.clear()
    this.notifyUpdate()
  }

  // 销毁
  destroy() {
    this.stop()
    this.updateCallback = null
    this.getMessagesLength = null
  }
}

// 单例
const danmakuManager = new DanmakuManager()

// 导出函数
export const startDanmaku = (updateCallback, getMessagesLengthCallback) => {
  danmakuManager.start(updateCallback, getMessagesLengthCallback)
}

export const stopDanmaku = () => danmakuManager.stop()
export const destroyDanmaku = () => danmakuManager.destroy()
export { XMLG_COLORS, danmuTexts }
export default danmakuManager
